package com.changgou.web.order.controller;

import com.changgou.entity.Result;
import com.changgou.order.feign.OrderFeign;
import com.changgou.order.pojo.Order;
import com.changgou.pay.feign.PayFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.Map;

/**
 * @Author LQQ
 * @Date 2020/3/15 18:04
 * @Version 1.0
 */

/**
 * 跳转到微信支付的二维码页面
 */
@Controller
@RequestMapping("/wxpay")
public class PayController {
    @Autowired
    private PayFeign payFeign;
    @Autowired
    private OrderFeign orderFeign;

    @GetMapping
    public String wxPay(String orderId, Model model) {
        //1. 根据orderId查询订单,如果订单不存在,跳转到错误页面
        Result<Order> orderResult = orderFeign.findById(orderId);

        if (orderResult.getData() == null) {
            return "fail";//错误页面
        }
        //2. 根据下单的支付状态进行判断,如果不是未支付的订单,跳转到错误页面
        Order order = orderResult.getData();

        String payStatus = order.getPayStatus();//支付状态

        if (!"0".equals(payStatus)) {
            //不是未支付的订单
            return "fail";
        }

        //3. 基于payFeign调用统计下单接口,并获取返回结果
        Result payResult = payFeign.nativePay(orderId, order.getPayMoney());

        //payResult封装了微信返回的结果
        if (payResult.getData() == null) {
            return "fail";
        }

        //4.封装结果数据
        Map payMap = (Map) payResult.getData();

        //二维码那有订单id跟钱
        payMap.put("orderId", orderId);

        payMap.put("payMoney", order.getPayMoney());

        //因为返回的是map所以用addAllAttributes
        model.addAllAttributes(payMap);

        return "wxpay";

    }

    /**
     * 支付成功页面的跳转
     * @param payMoney
     * @param model
     * @return
     */
    @RequestMapping("/toPaySuccess")
    //参数payMoney为页面跳转带过来的
    public String toPaySuccess(Integer payMoney,Model model){

        model.addAttribute("payMoney",payMoney);
        return "paysuccess";
}

}